<template>
  <el-drawer
      :title="operation === 'create' ? '创建字典' : '修改字典'"
      v-model="visible"
      width="40%"
      :destroy-on-close="true"
      @close="onCancel"
  >
    <!-- 表单内容 -->
    <el-form :model="dictForm" ref="dictFormRef" label-width="120px" class="styled-form">
      <el-form-item
          label="字典名称"
          prop="dictName"
          :rules="[{ required: true, message: '请输入字典名称', trigger: 'blur' }]"
      >
        <el-input v-model="dictForm.dictName" placeholder="请输入字典名称"></el-input>
      </el-form-item>

      <el-form-item
          label="字典中文名称"
          prop="dictNameCn"
          :rules="[{ required: true, message: '请输入字典中文名称', trigger: 'blur' }]"
      >
        <el-input v-model="dictForm.dictNameCn" placeholder="请输入字典中文名称"></el-input>
      </el-form-item>

      <el-form-item label="字典描述">
        <el-input
            v-model="dictForm.dictDescription"
            type="textarea"
            placeholder="请输入字典描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="所属模块">
        <DropdownDictSelect v-model="dictForm.module" :dictName="'ALL_MODULE'" :spaceId="dictForm.spaceId" />
      </el-form-item>

      <el-form-item label="所属空间">
        <el-input-number
            v-model="dictForm.spaceId"
            :min="0"
            placeholder="请输入所属空间"
            class="input-number"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="是否生效">
        <el-switch v-model="dictForm.isActive" :active-value="1" :inactive-value="0"></el-switch>
      </el-form-item>

      <el-form-item label="关联枚举类">
        <el-input v-model="dictForm.enumClass" placeholder="请输入枚举类全限定名称"></el-input>
      </el-form-item>
    </el-form>

    <!-- 底部操作按钮 -->
    <div class="drawer-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onSave">保存</el-button>
    </div>
  </el-drawer>
</template>

<script>
import { ref, toRefs, watch } from 'vue';
import { createDict, updateDict, getDictDetails } from '@/service/admin/admin.service';
import DropdownDictSelect from "@/components/dropdown/DropdownSelect.vue";
import {ElMessage} from "element-plus";

export default {
  components: {DropdownDictSelect},
  props: {
    modelValue: {
      type: Boolean,
      required: true
    },
    operation: {
      type: String,
      default: 'create'
    },
    dictId: {
      type: [String, Number],
      default: null
    }
  },
  emits: ['update:modelValue', 'close', 'save'],
  setup(props, { emit }) {
    const { modelValue, operation, dictId } = toRefs(props);
    const visible = ref(modelValue.value);

    watch(modelValue, (newValue) => {
      visible.value = newValue;
    });

    watch(visible, (newValue) => {
      emit('update:modelValue', newValue);
    });

    const dictForm = ref({
      dictName: '',
      dictNameCn: '',
      dictDescription: '',
      module: '',
      spaceId: 0,
      isActive: 1,
      enumClass: ''
    });

    const dictFormRef = ref(null);

    // 监听 operation 和 dictId 的变化，以确保在修改模式下回显数据
    watch([operation, dictId], async ([newOperation, newDictId]) => {
      if (newOperation === 'update' && newDictId) {
        // 如果是修改操作，获取字典详情并回显数据
        getDictDetails(newDictId, (response) => {
          if (response.status === 'success') {
            dictForm.value = { ...response.data };
          }
        });
      } else if (newOperation === 'create') {
        // 如果是创建操作，重置表单
        resetForm();
      }
    });

    // 重置表单
    const resetForm = () => {
      dictForm.value = {
        dictName: '',
        dictNameCn: '',
        dictDescription: '',
        module: '',
        spaceId: 0,
        isActive: 1,
        enumClass: ''
      };
    };

    // 保存操作
    const onSave = () => {
      dictFormRef.value.validate((valid) => {
        if (valid) {
          const params = {
            dictName: dictForm.value.dictName,
            dictNameCn: dictForm.value.dictNameCn,
            dictDescription: dictForm.value.dictDescription,
            enumClass: dictForm.value.enumClass,
            isActive: dictForm.value.isActive,
            module: dictForm.value.module,
            spaceId: dictForm.value.spaceId
          };

          // 根据操作类型选择请求方法
          if (operation.value === 'create') {
            createDict(
                params,
                (response) => {
                  if (response.status === 'success') {
                    console.log('创建成功:', response);
                    emit('save');
                    emit('update:modelValue', false); // 关闭 Drawer
                  } else {
                    console.error('创建失败:', response.message);
                    // 提示错误信息
                    ElMessage({
                      message: response.message || '创建失败',
                      type: 'error',
                    });
                  }
                },
                (error) => {
                  console.error('请求出错:', error);
                  ElMessage({
                    message: '请求失败，请稍后重试',
                    type: 'error',
                  });
                }
            );
          } else {
            params.id = dictId.value;
            // 调用 updateDict 方法进行修改
            updateDict(
                params,
                (response) => {
                  console.log('更新成功:', response);
                  emit('save');
                  emit('update:modelValue', false); // 关闭 Drawer
                },
                (error) => {
                  console.error('更新失败:', error);
                }
            );
          }
        } else {
          console.log('表单验证失败');
        }
      });
    };

    const onCancel = () => {
      emit('update:modelValue', false); // 关闭 Drawer
    };

    return {
      visible,
      dictForm,
      dictFormRef,
      onSave,
      onCancel
    };
  }
};
</script>


<style scoped>
.styled-form {
  max-width: 600px;
  margin: 0 auto;
}

.input-number {
  width: 100%;
}

.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.drawer-footer .el-button {
  margin-left: 10px;
}
</style>
